import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import { Modal, notification } from 'ant-design-vue'
import {
  ACCESS_TOKEN
} from "@/store/mutation-types"
import { IS_SKIPED } from '../store/mutation-types'
const notificationKey = 'tokenInvalid';//token失效提示弹框的key 避免重复弹出
// 创建 axios 实例
const service = axios.create({
  baseURL:window._CONFIG['domianURL'],
  timeout: 60000 // 请求超时时间
})

const err = (error) => {
  console.log(error)
  //这个判断是解决同时打开两个系统，其中一个退出登录后，另一个系统再调接口报跨域错误，没有弹出重新登录
  if(error && error=='Error: Network Error'){
    // alert('Error: Network Error登录过期')
    console.log('Error: Network Error登录过期')
    Vue.ls.remove(ACCESS_TOKEN)
    // window.location.reload()
  }else if (error.response) {
    let data = error.response.data
    // console.log(data)
    const token = Vue.ls.get(ACCESS_TOKEN)
    console.log("------异常响应------", token)
    console.log("------异常响应------", error.response.status)
    switch (error.response.status) {
      case 403:
        notification.error({
          message: '系统提示',
          description: '拒绝访问',
          duration: 4
        })
        break
      case 500:
        //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
        if (((data.message === 'Token is invalid,please login again') || (data.message === 'org.apache.shiro.authc.AuthenticationException: Token is invalid,please login again'))) {
          let secondsToGo = 3
          notification.error({
            key: notificationKey,
            message: '系统提示',
            description: `登录已过期，${secondsToGo}s后自动退出重新登录!`,
            duration: null
          })

          setTimeout(() => {
            console.log(Vue.ls.get(IS_SKIPED))
            if(Vue.ls.get(IS_SKIPED)){
              console.log('_________跳转过来token失效，重新登录_________')
              console.log('__________________')
              window.location.href =window._CONFIG['anotherSystemBrowserURL']+'/#/user/login'
            }else{
              Vue.ls.remove(ACCESS_TOKEN)
              window.location.reload()
            }
            // console.log(secondsToGo)
          }, secondsToGo * 1000)
        }
        break
      case 404:
        notification.error({
          message: '系统提示',
          description: '很抱歉，资源未找到!',
          duration: 4
        })
        break
      case 504:
        notification.error({
          message: '系统提示',
          description: '网络超时'
        })
        break
      case 401:
        notification.error({
          message: '系统提示',
          description: '未授权，请重新登录',
          duration: 4
        })
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  // console.log(token)
  if (token) {
    config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if (config.method == 'get') {
    config.params = {
      _t: Date.parse(new Date()) / 1000,
      ...config.params
    }
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
  // console.log(response)
  const token = Vue.ls.get(ACCESS_TOKEN)
  switch (response.data.code){
    case 500:
      if(response.data.message === "Token is invalid,please login again") {
        //如果是获取授权列表接口token失效 直接跳转到登录页
        // console.log(response)
        let secondsToGo = 3
        notification.error({
          key: notificationKey,
          message: '系统提示',
          description: `很抱歉，登录已过期，${secondsToGo}s后将自动退出重新登录!`,
          duration: null
        })
        setTimeout(() => {
          console.log(Vue.ls.get(IS_SKIPED))
          if(Vue.ls.get(IS_SKIPED)){
            console.log('_________跳转过来token失效，重新登录_________')
            window.location.href =window._CONFIG['anotherSystemBrowserURL']+'/#/user/login'
          }else{
            Vue.ls.remove(ACCESS_TOKEN)
            window.location.reload()
          }
          // console.log(secondsToGo)
        }, (secondsToGo - 1) * 1000)

      }else{
        return response.data
      }
      break;
    case 404:
      notification.error({
        message: '系统提示',
        description: '很抱歉，资源未找到!',
        duration: 4
      })
      break
    case 504:
      notification.error({
        message: '系统提示',
        description: '网络超时'
      })
      break
    case 401:
      notification.error({
        message: '系统提示',
        description: '未授权，请重新登录',
        duration: 4
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
      break
    default:
      return response.data
      break;
  }

  return response.data
}, err)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}